package cn.vc.media.service.impl;

import cn.vc.auth.entity.po.VUser;
import cn.vc.basicmodule.utils.StringUtil;
import cn.vc.basicmodule.entity.Result;
import cn.vc.media.entity.po.MediaFiles;
import cn.vc.media.mapper.MediaFilesMapper;
import cn.vc.media.service.BigFileService;
import cn.vc.media.util.SecurityUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description TODO
 * @author Mr.M
 * @date 2022/9/10 8:58
 * @version 1.0
 */
@Slf4j
@Service
public class BigFileServiceImpl implements BigFileService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private BigFileService currentProxy;
    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    // Minio IP地址
    @Value("${minio.ip}")
    private String ip;
    // 存储封面
    @Value("${minio.bucket.coverfiles}")
    private String bucket_cover;
    // 存储视频
    @Value("${minio.bucket.videofiles}")
    private String bucket_video;

    // 根据扩展名获取mimeType
    private String getMimeType(String extension) {
        if (extension==null) {
            extension = "";
        }
        // 通过扩展名得到媒体资源类型 mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE; // 通用mimeType，字节流
        if (extensionMatch!=null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    /**
     * 将文件上传到minio
     * @param localFilePath 文件本地路径
     * @param mimeType 媒体类型
     * @param bucket 桶
     * @param objectName 对象名
     * @return
     */
    @Override
    public boolean addMediaFilesToMinio(String localFilePath, String mimeType, String bucket, String objectName) {
        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket) // 桶
                    .filename(localFilePath) // 指定本地文件路径
                    .object(objectName) // 对象名 放在子目录下
                    .contentType(mimeType) // 设置媒体文件类型
                    .build();
            minioClient.uploadObject(uploadObjectArgs);
            log.debug("上传文件到minio成功,bucket:{},objectName:{}",bucket,objectName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件出错,bucket:{},objectName:{},错误信息:{}", bucket, objectName, e.getMessage());
        }
        return false;
    }

    /**
     * 将文件信息添加到文件夹
     * @param fileMd5 文件md5值
     * @param bucket 桶
     * @param objectName 对象名称
     * @return
     */
    @Transactional
    @Override
    public MediaFiles addMediaFilesToDb(String fileMd5, String bucket, String objectName, String fileType) {
        // 将文件信息保存到数据库
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles==null) {
            mediaFiles = new MediaFiles();
            // 文件id
            mediaFiles.setId(fileMd5);
            VUser vUser = SecurityUtil.getUser();
            if (vUser==null) {
                log.debug("向数据库保存文件失败，bucket：{}objectName：{}，用户为空", bucket, objectName);
                return null;
            }
            // 上传用户ID
            mediaFiles.setUserId(vUser.getId());
            // 文件名称
            mediaFiles.setFileMd5(fileMd5);
            // 文件类型
            mediaFiles.setFileType(fileType);
            // 桶
            mediaFiles.setBucket(bucket);
            // file_path
            mediaFiles.setFilePath(objectName);
            // url
            mediaFiles.setUrl("http://"+this.ip+"/minio/"+bucket+"/"+objectName);
            // 上传时间
            mediaFiles.setCreateDate(LocalDateTime.now());
            // 插入数据库
            int insert = mediaFilesMapper.insert(mediaFiles);
            if (insert<=0) {
                log.debug("向数据库保存文件失败，bucket：{}objectName：{}", bucket, objectName);
                return null;
            }
            return mediaFiles;
        }
        return mediaFiles;
    }

    @Override
    public Result<?> checkFile(String fileMd5) {
        // 先查询数据库
        MediaFiles mediaFiles = mediaFilesMapper.selectOne(new LambdaQueryWrapper<MediaFiles>().eq(MediaFiles::getFileMd5, fileMd5));
        if (mediaFiles!=null) {
            // 桶
            String bucket = mediaFiles.getBucket();
            // objectName
            String filePath = mediaFiles.getFilePath();
            // 如果数据库存在再查询minio
            GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(filePath)
                    .build();
            // 查询远程服务器获取到一个流对象
            try {
                FilterInputStream inputStream = minioClient.getObject(getObjectArgs);
                if (inputStream!=null) {

                    return new Result<>(true, mediaFiles.getId(), null);
                }
            } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                     IOException | InvalidResponseException | NoSuchAlgorithmException | ServerException |
                     XmlParserException e) {
                e.printStackTrace();
            }
        }
        // 文件不存在
        return new Result<>(false);
    }

    @Override
    public boolean checkChunk(String fileMd5, int chunkIndex) {
        // 分块存储路径是：md5前两位为两个目录，chunk存储分块文件
        // 根据md5得到分块文件的路径
        String chunkFileFolderPath = this.getChunkFileFolderPath(fileMd5);
        // 如果数据库存在再查询minio
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucket_video)
                .object(chunkFileFolderPath+chunkIndex)
                .build();
        // 查询远程服务器获取到一个流对象
        try {
            FilterInputStream inputStream = minioClient.getObject(getObjectArgs);
            if (inputStream!=null) {
                return true;
            }
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 IOException | InvalidResponseException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 得到分块文件的目录
    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.charAt(0) + "/" + fileMd5.charAt(1) + "/" + fileMd5 + "/chunk/";
    }

    @Override
    public Result<?> uploadChunk(String fileMd5, int chunk, String localChunkFilePath) {
        // 分块文件的路径
        String chunkFilePath = getChunkFileFolderPath(fileMd5) + chunk;
        // 获取mimeType
        String mimeType = getMimeType(null);
        // 将分块上传到minio
        boolean b = this.addMediaFilesToMinio(localChunkFilePath, mimeType, bucket_video, chunkFilePath);
        if (!b) {
            return new Result<>(false, chunk, "上传分块文件信息失败");
        }
        return new Result<>(true, chunk, null);
    }

    @Override
    public Result<?> mergechunks(String fileMd5, int chunkTotal, String filename) {
        // 分块文件所在目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        // 找到所有的分块文件调用minio的sdk进行文件合并
        List<ComposeSource> sources = Stream.iterate(0, i -> ++i)
                .limit(chunkTotal)
                .map(i -> ComposeSource.builder().bucket(bucket_video).object(chunkFileFolderPath + i).build())
                .collect(Collectors.toList());
        // 扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        // 合并后文件的objectName
        String objectName = getFilePathByMd5(fileMd5, extension);
        ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder()
                .bucket(bucket_video)
                .object(objectName)
                .sources(sources) // 指定源文件
                .build();
        // 合并文件
        try {
            minioClient.composeObject(composeObjectArgs);
        } catch (ErrorResponseException | InsufficientDataException | InvalidResponseException | InternalException |
                 InvalidKeyException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            e.printStackTrace();
            log.error("合并文件出错，bucket:{},objectName:{},错误信息:{}", bucket_video, objectName, e.getMessage());
            return new Result<>(false, null, "合并文件异常");
        }
        //=====================校验合并后的和源文件是否一致，视频上传才成功===================//
        // 先下载合并后的文件
        File file = this.downloadFileFromMinIO(bucket_video, objectName);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            // 计算合并后文件的md5
            String mergeFile_md5 = DigestUtils.md5Hex(fileInputStream);
            // 比较原始的md5和合并后文件的md5
            if (!fileMd5.equals(mergeFile_md5)) {
                log.error("校验合并文件md5值不一致，原始文件：{}，合并文件：{}", fileMd5, mergeFile_md5);
                return new Result<>(false, null, "文件校验失败");
            }
        } catch (IOException e) {
            return new Result<>(false, null, "文件校验失败");
        }

        //======================将文件信息入库=================//
        MediaFiles mediaFiles = currentProxy.addMediaFilesToDb(fileMd5, bucket_video, objectName, extension);
        if (mediaFiles == null) {
            log.error("文件入库失败");
            return new Result<>(false, null,  "文件入库失败");
        }

        //=====================清理分块文件===================//
        this.clearChunkFiles(chunkFileFolderPath, chunkTotal);

        return new Result<>(true, mediaFiles, null);
    }

    /**
     * 清楚分块文件
     * @param chunkFileFolderPath 分块文件路径
     * @param chunkTotal 分块文件总数
     */
    private void clearChunkFiles(String chunkFileFolderPath, int chunkTotal) {
        Iterable<DeleteObject> objects = Stream.iterate(0, i -> ++i)
                .limit(chunkTotal)
                .map(i -> new DeleteObject(chunkFileFolderPath.concat(Integer.toString(i))))
                .collect(Collectors.toList());
        RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder()
                .bucket(bucket_video)
                .objects(objects)
                .build();
        Iterable<io.minio.Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
        // 要想真正删除
        results.forEach(f->{
            try {
                DeleteError deleteError = f.get();
            } catch (ErrorResponseException | InsufficientDataException | InternalException | IOException |
                     InvalidResponseException | NoSuchAlgorithmException | InvalidKeyException | ServerException |
                     XmlParserException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public File downloadFileFromMinIO(String bucket,String objectName){
        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;
        try{
            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .build());
            //创建临时文件
            minioFile=File.createTempFile("minio", ".merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(stream,outputStream);
            return minioFile;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 得到合并后的文件的地址
     * @param fileMd5 文件id即md5值
     * @param fileExt 文件扩展名
     * @return
     */
    private String getFilePathByMd5(String fileMd5,String fileExt){
        return   fileMd5.charAt(0) + "/" + fileMd5.charAt(1) + "/" + fileMd5 + "/" + fileMd5 +fileExt;
    }

}
